package com.XinYun.Library.modules.display.controller.Servlet;

import com.XinYun.Library.modules.commons.BasicServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.XinYun.Library.modules.display.controller.displayImpl;
import com.XinYun.Library.modules.display.dao.sqlexecutor;
import com.XinYun.Library.modules.display.response.ResponseWrapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.XinYun.Library.modules.display.dao.sqlexecutor;
@WebServlet(name = "GetAllLogServlet",urlPatterns= "/displayServlet")
public class displayServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求体数据
        BufferedReader reader = req.getReader();
        String readLine = reader.readLine();
        //将JSON字符转化为JAVA对象
        JSONObject jsonObject = JSON.parseObject(readLine);
        String value = jsonObject.getString("search");
        //调用方法，执行语句
        String sql = "SELECT bookname,num,loan,`like` from books_info WHERE bookname LIKE ? or category LIKE ?;";
        displayImpl displayImpl = new displayImpl();
        //执行加判断
        try {
            displayImpl.getALL(sql,value);
            ResultSet resultSet = sqlexecutor.select(sql,value);
            if(resultSet.next()){
                //如果数据库中能查询到相关信息，将方法返回的数据转化为JSON字符串，传给前端
                String s = JSON.toJSONString(displayImpl.getALL(sql,value));
                PrintWriter writer = resp.getWriter();
                writer.println(s);
                System.out.println(s);
            }else {
                //如果书库中没有此书籍，则返回错误信息
                ResponseWrapper responseWrapper=null;
                responseWrapper = ResponseWrapper.error();
                String s=JSON.toJSONString(responseWrapper);
                PrintWriter writer = resp.getWriter();
                writer.println(s);
                System.out.println(s);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    }



